package com.pf.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加解密
 * <p>
 * 算法：AES
 * 密钥长度：128
 * 工作模式：ECB
 * 填充方式：PKCS5Padding
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/2/13 13:34
 */
@Slf4j
public class EAESUtils {

    public static void main(String[] args) {
        String oriStr = "测试AES加解密";
        String aesKey = getAesKey();
        String encryptStr = encrypt(oriStr, aesKey);
        String decryptStr = decrypt(encryptStr, aesKey);
        System.out.println("原字符串：" + oriStr);
        System.out.println("加密字符串：" + encryptStr);
        System.out.println("解密字符串：" + decryptStr);
    }

    /**
     * 生成128位 aesKey
     *
     * @return
     */
    public static String getAesKey() {
        try {
            //生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] keyBytes = secretKey.getEncoded();
            //key转换
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            String aesKey = Base64.encodeBase64String(secretKeySpec.getEncoded());
            return aesKey;
        } catch (Exception e) {
            log.error("AesUtils getAesKey error", e);
        }
        return null;
    }

    /**
     * 获取aes key
     *
     * @param keyStr
     * @return
     */
    private static SecretKeySpec getAesKey(String keyStr) {
        if (keyStr == null || "".equals(keyStr)) {
            return null;
        }
        return new SecretKeySpec(Base64.decodeBase64(keyStr), "AES");
    }

    /**
     * aes加密
     *
     * @param oriStr
     * @param keyStr
     * @return
     */
    public static String encrypt(String oriStr, String keyStr) {
        try {
            SecretKeySpec aesKey = getAesKey(keyStr);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] bytes = cipher.doFinal(oriStr.getBytes());
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            log.error("AesUtils encrypt error", e);
        }
        return null;
    }

    /**
     * aes 解密
     *
     * @param encryptStr
     * @param keyStr
     * @return
     */
    public static String decrypt(String encryptStr, String keyStr) {

        try {
            SecretKeySpec aesKey = getAesKey(keyStr);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            byte[] bytes = cipher.doFinal(Base64.decodeBase64(encryptStr));
            return new String(bytes);
        } catch (Exception e) {
            log.error("AesUtils decrypt error", e);
        }
        return null;
    }
}
